﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Reflection;

namespace IDRead_CVR
{
    [ComVisible(true)]
    [Guid("B7E6AA9D-68AC-4BC9-8AC2-D19C66020B7F")]
    [ClassInterface(ClassInterfaceType.None)]
    [ComDefaultInterface(typeof(IComReader))]
    [ComSourceInterfaces(typeof(IComReaderEvent))]
    public class ComReader : UserControl, IComReader, IObjectSafety
    {
        public bool ReadCard(int port)
        {
            if (deviceOpened)
                return true;
            if ((port > 0 && port < 17) || (port > 1000 && port < 1017))
            {
                var rtnResult = 0;
                if (port > 1000 && port < 1017)
                {
                    for (int i = 1001; i < 1017; i++)
                    {
                        rtnResult = CVRSDK.CVR_InitComm(port);
                        if (rtnResult == 1)
                            break;
                    }
                }
                else
                {
                    rtnResult = CVRSDK.CVR_InitComm(port);
                }
                if (rtnResult == 1)
                {
                    deviceOpened = true;
                    if (!GetThreadState())
                    {
                        thdReading = new Thread(new ThreadStart(DoWork));
                        thdReading.IsBackground = true;
                        thdReading.Start();
                    }
                    return true;
                }
                else
                {
                    ReadCompleteEventArgs args = new ReadCompleteEventArgs();
                    args.ReadStateCode = "2";
                    args.ReadStateMessage = "打开读卡器设备[" + port + "]失败";
                    TriggerReadCompleteEvent(args);
                    return false;
                } 
            }
            else
            {
                ReadCompleteEventArgs args = new ReadCompleteEventArgs();
                args.ReadStateCode = "1";
                args.ReadStateMessage = "参数端口不符合规范";
                TriggerReadCompleteEvent(args);
                return false;
            }
        }

        public bool Close()
        {
            if (GetThreadState())
            {
                try
                {
                    thdReading.Abort();
                }
                catch (ThreadAbortException)
                {
                }
            }
            CVRSDK.CVR_CloseComm();
            deviceOpened = false;
            return true;
        }

        public event ReadCompleteEventHandler ReadComplete;
        private static Thread thdReading;
        private static bool deviceOpened = false;

        private void DoWork()
        {
            while (true)
            {
                Thread.Sleep(300);
                var authenticate = CVRSDK.CVR_Authenticate();
                if (authenticate == 1)
                {
                    int readContent = CVRSDK.CVR_Read_Content(4);
                    if (readContent == 1)
                    {
                        byte[] name = new byte[30];
                        int length = 30;
                        CVRSDK.GetPeopleName(ref name[0], ref length);
                        byte[] number = new byte[30];
                        length = 36;
                        CVRSDK.GetPeopleIDCode(ref number[0], ref length);
                        byte[] people = new byte[30];
                        length = 3;
                        CVRSDK.GetPeopleNation(ref people[0], ref length);
                        byte[] validtermOfStart = new byte[30];
                        length = 16;
                        CVRSDK.GetStartDate(ref validtermOfStart[0], ref length);
                        byte[] birthday = new byte[30];
                        length = 16;
                        CVRSDK.GetPeopleBirthday(ref birthday[0], ref length);
                        byte[] address = new byte[30];
                        length = 70;
                        CVRSDK.GetPeopleAddress(ref address[0], ref length);
                        byte[] validtermOfEnd = new byte[30];
                        length = 16;
                        CVRSDK.GetEndDate(ref validtermOfEnd[0], ref length);
                        byte[] signdate = new byte[30];
                        length = 30;
                        CVRSDK.GetDepartment(ref signdate[0], ref length);
                        byte[] sex = new byte[30];
                        length = 3;
                        CVRSDK.GetPeopleSex(ref sex[0], ref length);

                        byte[] samid = new byte[32];
                        CVRSDK.CVR_GetSAMID(ref samid[0]);

                        ReadCompleteEventArgs args = new ReadCompleteEventArgs();

                        args.Address = System.Text.Encoding.GetEncoding("GB2312").GetString(address).Replace("\0", "").Trim();
                        args.Gender = System.Text.Encoding.GetEncoding("GB2312").GetString(sex).Replace("\0", "").Trim();
                        args.Birthday = DateTime.Parse(System.Text.Encoding.GetEncoding("GB2312").GetString(birthday).Replace("\0", "").Trim());
                        //args. = System.Text.Encoding.GetEncoding("GB2312").GetString(signdate).Replace("\0", "").Trim();
                        args.IDCardCode = System.Text.Encoding.GetEncoding("GB2312").GetString(number).Replace("\0", "").Trim();
                        args.PeopleName = System.Text.Encoding.GetEncoding("GB2312").GetString(name).Replace("\0", "").Trim();
                        args.Nation = System.Text.Encoding.GetEncoding("GB2312").GetString(people).Replace("\0", "").Trim();
                        // = "安全模块号：" + System.Text.Encoding.GetEncoding("GB2312").GetString(samid).Replace("\0", "").Trim();
                        args.ValidateStartDate = DateTime.Parse(System.Text.Encoding.GetEncoding("GB2312").GetString(validtermOfStart).Replace("\0", "").Trim());
                        args.ValidateEndDate = DateTime.Parse(System.Text.Encoding.GetEncoding("GB2312").GetString(validtermOfEnd).Replace("\0", "").Trim());
                        args.ReadStateCode = "0";
                        args.ImagePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "zp.bmp");
                        TriggerReadCompleteEvent(args);
                        break;
                    }
                }
            }
        }

        private void TriggerReadCompleteEvent(ReadCompleteEventArgs args)
        {
            deviceOpened = false;
            var handler = ReadComplete;
            if (handler != null)
            {
                if (this.InvokeRequired)
                {
                    this.BeginInvoke(handler, args);
                }
                else
                {
                    handler(args);
                }
            }
        }


        private static bool GetThreadState()
        {
            return thdReading != null &&
                                    (thdReading.ThreadState == ThreadState.Running ||
                                    thdReading.ThreadState == ThreadState.Background ||
                                    thdReading.ThreadState == ThreadState.Suspended ||
                                    thdReading.ThreadState == ThreadState.SuspendRequested);
        }

        #region IObjectSafety 成员

        private const string _IID_IDispatch = "{00020400-0000-0000-C000-000000000046}";
        private const string _IID_IDispatchEx = "{a6ef9860-c720-11d0-9337-00a0c90dcaa9}";
        private const string _IID_IPersistStorage = "{0000010A-0000-0000-C000-000000000046}";
        private const string _IID_IPersistStream = "{00000109-0000-0000-C000-000000000046}";
        private const string _IID_IPersistPropertyBag = "{37D84F60-42CB-11CE-8135-00AA004BB851}";
        private const int INTERFACESAFE_FOR_UNTRUSTED_CALLER = 0x00000001;
        private const int INTERFACESAFE_FOR_UNTRUSTED_DATA = 0x00000002;
        private const int S_OK = 0;
        private const int E_FAIL = unchecked((int)0x80004005);
        private const int E_NOINTERFACE = unchecked((int)0x80004002);
        private bool _fSafeForScripting = true;
        private bool _fSafeForInitializing = true;

        public int GetInterfaceSafetyOptions(ref Guid riid, ref int pdwSupportedOptions, ref int pdwEnabledOptions)
        {
            int Rslt = E_FAIL;
            string strGUID = riid.ToString("B");
            pdwSupportedOptions = INTERFACESAFE_FOR_UNTRUSTED_CALLER | INTERFACESAFE_FOR_UNTRUSTED_DATA;

            switch (strGUID)
            {
                case _IID_IDispatch:
                case _IID_IDispatchEx:
                    Rslt = S_OK; pdwEnabledOptions = 0;
                    if (_fSafeForScripting == true)
                        pdwEnabledOptions = INTERFACESAFE_FOR_UNTRUSTED_CALLER;
                    break;
                case _IID_IPersistStorage:
                case _IID_IPersistStream:
                case _IID_IPersistPropertyBag:
                    Rslt = S_OK;
                    pdwEnabledOptions = 0;
                    if (_fSafeForInitializing == true)
                        pdwEnabledOptions = INTERFACESAFE_FOR_UNTRUSTED_DATA;
                    break;
                default:
                    Rslt = E_NOINTERFACE;
                    break;
            }
            return Rslt;
        }

        public int SetInterfaceSafetyOptions(ref Guid riid, int dwOptionSetMask, int dwEnabledOptions)
        {
            int Rslt = E_FAIL;
            string strGUID = riid.ToString("B");

            switch (strGUID)
            {
                case _IID_IDispatch:
                case _IID_IDispatchEx:
                    if (((dwEnabledOptions & dwOptionSetMask) == INTERFACESAFE_FOR_UNTRUSTED_CALLER) && (_fSafeForScripting == true))
                        Rslt = S_OK;
                    break;
                case _IID_IPersistStorage:
                case _IID_IPersistStream:
                case _IID_IPersistPropertyBag:
                    if (((dwEnabledOptions & dwOptionSetMask) == INTERFACESAFE_FOR_UNTRUSTED_DATA) && (_fSafeForInitializing == true))
                        Rslt = S_OK;
                    break;
                default:
                    Rslt = E_NOINTERFACE;
                    break;
            }

            return Rslt;
        }

        #endregion
    }
}
